using System;
using System.Collections.Generic;
using System.Text;
using Barrage.Global;
using Barrage.Global.Vertex;
using SlimDX.Direct3D9;
using SlimDX;

namespace Barrage.Meshes
{
    /// <summary>
    /// A mesh that renders a simple cube
    /// </summary>
    public class Cube:Barrage.Mesh
    {
        static SlimDX.Direct3D9.Mesh cubeMesh = null;

        static void initializeBuffer()
        {
            cubeMesh = SlimDX.Direct3D9.Mesh.CreateBox(Engine.Device, 1, 1, 1);            
            Engine.RegisterDisposeHandler(new EngineDisposeHandler(disposeBuffer));
        }

        /// <summary>
        /// Constructor. Creates the cube mesh if necessary
        /// </summary>
        public Cube()
        {
            if (cubeMesh == null)
                initializeBuffer();
            materials.Add(new Material());
        }

        /// <summary>
        /// \internal Renders the cube to screen
        /// </summary>
        /// <param name="item">Item that's rendering this mesh</param>
        public override void Render(Barrage.Item item)
        {
            shader.BeginRender(item, materials[0]);
            int passNumber = shader.PassNumber(materials[0]);
            for (int j = 0; j < passNumber; j++)
            {
                shader.BeginPass(j);
                cubeMesh.DrawSubset(0);
                shader.EndPass();
            } 
            shader.EndRender();
            
            NLog.LogManager.GetLogger("Barrage::Scene::Graphics3D::Cube").Debug("Rendering Cube");
        }

        /// <summary>
        /// Clear static resources
        /// </summary>
        static void disposeBuffer()
        {
            if (cubeMesh != null)
                cubeMesh.Dispose();
            cubeMesh = null;
            NLog.LogManager.GetCurrentClassLogger().Debug("Disposing mesh");
        }
    }
}
